package com.tron.utils;

import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;

@Component
public class SocketClient{
    public void send(String message) {
        //String host = "127.0.0.1"; // 服务器地址
        String host = "localhost"; // 服务器地址
        int port = 1234; // 服务器端口
        Socket socket = null;
        OutputStream os = null;
        InputStream is = null;

        try {
            // 创建Socket连接
            socket = new Socket(InetAddress.getByName(host), port);

            // 获取输出流
            os = socket.getOutputStream();

            // 将数据转换为字节并发送
            os.write(message.getBytes());
            System.out.println("Data sent successfully.");

            // 获取输入流
            is = socket.getInputStream();

            // 读取客户端发送的数据
            byte[] buffer = new byte[1024];
            int bytesRead = -1;
            while ((bytesRead = is.read(buffer)) != -1) {
                String receive = new String(buffer, 0, bytesRead);
                System.out.println("Received message: " + receive);
            }


        } catch (IOException e) {
            System.out.println("ininininniini");
            e.printStackTrace();
        } finally {
            // 关闭资源
//            try {
//                if (os != null) os.close();
//                if (socket != null) socket.close();
//            } catch (IOException e) {
//                System.out.println("有异常....");
//                e.printStackTrace();
//            }
        }
    }
}